<?php
namespace Api\Controller;
use Think\Controller;

require_once "./ThinkPHP/Library/Vendor/WxShaoMa_v3/lib/WxPay.Api.php";
require_once './ThinkPHP/Library/Vendor/WxShaoMa_v3/lib/WxPay.Notify.php';

class WxShaoMaController extends Controller {

    /**微信支付页面*/
    public function wxShaoMa(){
        if(IS_POST){
            $data = I('post');
            $data['user_id'] = 1;
            $data['order_no'] = get_order_no();
            $data['create_date'] = date('Y-m-d H:i:s');
            //微信支付
            if($data['pay_type'] == 1){
                $this->wxShaoMaDoing($data);
            }
            //注：新版支付宝PHP >= 5.5
        }else{
            $this->display();
        }
    }
    /**
     *微信扫码提交数据后的处理
     *
     */
    public function wxShaoMaDoing($data)
    {
        //微信WEB配置信息，其它配置在SDK lib目录下的WxPay.Config.php文件中
        $web_weixin_config = C('WEB_WEIXINPAY_CONFIG');
        $data['notify_url'] = $web_weixin_config['notify_url'];
//        var_dump($data);die;
        require_once "./ThinkPHP/Library/Vendor/WxShaoMa_v3/lib/WxPay.Api.php";
        require_once "./ThinkPHP/Library/Vendor/WxShaoMa_v3/example/WxPay.NativePay.php";
        require_once './ThinkPHP/Library/Vendor/WxShaoMa_v3/example/log.php';
        require_once "./ThinkPHP/Library/Vendor/WxShaoMa_v3/lib/WxPay.Api.php";
        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['order_name']);   //商品描述
//        $input->SetAttach("test");
        $input->SetOut_trade_no($data['order_num']);   //商户订单号
//        $input->SetTotal_fee($data['order_totalprice']*100);  //价格以分为单位
        $input->SetTotal_fee(1);  //价格以分为单位
//        $input->SetTime_start(date("YmdHis"));
//        $input->SetTime_expire(date("YmdHis", time() + 600));
//        $input->SetGoods_tag("test");
        $input->SetNotify_url($data['notify_url']);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($data['goods_id']);
        $result = $notify->GetPayUrl($input);
        //生成二维码图片
        $this->assign('codeUrl',urlencode($result["code_url"]));
        //以下是二维页面显示的数据
        $this->assign('id',$data['order_id']);//订单id
        $this->assign('goods_name',$data['order_name']);
        $this->assign('order_totalprice',$data['order_totalprice']);
        $this->assign('goods_id',$data['goods_id']);
        $this->assign('order_num',$data['order_num']);
        $this->display('wxShaoMaImg');
    }
    //生成二维码
    public function setWxShaoMaImg($codeUrl)
    {
        require_once './ThinkPHP/Library/Vendor/WxShaoMa_v3/example/phpqrcode/phpqrcode.php';
        \QRcode::png(urldecode($codeUrl));
    }
    
    //微信扫描二维码支付时，二维码处ajax请求来判断用户是否支付成功然后跳转
    public function getOrderStatus()
    {
        if(IS_AJAX){
            $product_id = I('product_id');
            $order_no = I('order_no');
            $user_id = 1;
            $order_data = M('order_pay_test')
                ->field('order_id,order_status')
                ->where(array('user_id'=>$user_id,'product_id'=>$product_id,'order_no'=>$order_no))
                ->find();
            if(!empty($order_data)){
                if($order_data['order_status'] == 0){
                    $data = array('code'=>1,'msg'=>'订单还未付款！');
                }else if($order_data['order_status'] == 1){
                    $data = array('code'=>0,'msg'=>'订单支付成功！');
                }
            }else{
                $data = array('code'=>1,'msg'=>'该订单不存在！');
            }
            $this->ajaxReturn($data);
        }
    }

    /**
     * 微信扫码支付异步回调方法
     *
     */
    public function wxNotifyUrlShaoMa()
    {
        $notify = new WxShaoMaNotifyController();
        $notify->Handle(false);
    }
}


/**
 *微信支付异步回调处理类
 */

class WxShaoMaNotifyController extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        // var_dump($data);die;
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            return false;
        }

        /**处理网站中订单相关的业务 成功返回true即可*/
        if($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS'){
            //查询订单数据 未支付时进行处理
            $orderData = M('order')
                ->field('order_id,order_paystatus')
                ->where(array('order_num'=>$data['out_trade_no']))
                ->find();
//            var_dump($data);
//            var_dump($orderData);
            if(!empty($orderData) && $orderData['order_paystatus'] == 1){
                $updateData = array(
                    'order_id' => $orderData['order_id'],
                    'order_paystatus' => 2,
                );
                $updateRes = M('order')->save($updateData);
                if($updateRes){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}
